package com.my.study.alibaba;

import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Carlos
 * @version 1.0.0
 * @date 2023/2/24 18:33
 */
public class StrMerge {

    public static void main(String[] args) {
        String str = "yujwedjhccdskdsewirewrwsadm,fnsdklwweqpq";
        // 1.获取ww之间的字符串
        String linkStrByWw = getLinkStrByWw(str, 'w');
        char[] chars = linkStrByWw.toCharArray();
        // 2.归并排序
        sort(chars, 0, chars.length -1);
        // 3.结果
        String newStr = new String(chars);
    }
    
    private static String getLinkStrByWw(String str, char c) {
        if (StrUtil.isBlank(str)) {
            return "";
        }

        List<Integer> positionList = new ArrayList<>();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == c) {
                positionList.add(i);
            }
        }
        
        List<String> result = new ArrayList<>();
        for (int i = 0; i < positionList.size() - 1; i++) {
           String subStr = str.substring(positionList.get(i) + 1, positionList.get(i + 1));
           result.add(subStr);
        }
        
        StringBuilder sb = new StringBuilder();
        for (String s : result) {
            sb.append(s);
        }
        
        return sb.toString();
    }
    
    
    private static void sort(char[] a, int start, int end) {
        if (null == a || start >= end) {
            return;
        }
        int mid = start + (end - start) / 2;
        sort(a, start, mid);
        sort(a, mid + 1, end);
        merge(a, start, mid, end);
    }
    
    
    private static void merge(char[] a, int start, int mid, int end) {
        char[] tmp = new char[end - start + 1];
        int index = 0;
        int lIndex = start;
        int rIndex = mid + 1;
        
        while (lIndex <= mid && rIndex <= end) {
            if (a[lIndex] < a[rIndex]) {
                tmp[index++] = a[lIndex++];
            }
            else {
                tmp[index++] = a[rIndex++];
            }
        }
        
        while (lIndex <= mid) {
            tmp[index++] = a[lIndex++];
        }
        
        while (rIndex <= end) {
            tmp[index++] = a[rIndex++];
        }

        for (int i = 0; i < index; i++) {
            a[start + i] = tmp[i];
        }
        
        tmp = null;
    }
}
